#!/usr/bin/env python
"""
Build the rtm component library
"""
#pylint: disable=unused-wildcard-import, wildcard-import, multiple-imports
#pylint: disable=wrong-import-position, invalid-name, too-many-locals
import os, sys

CIMEROOT = os.environ.get("CIMEROOT")
if CIMEROOT is None:
    raise SystemExit("ERROR: must set CIMEROOT environment variable")
sys.path.append(os.path.join(CIMEROOT, "scripts", "Tools"))

from standard_script_setup import *
from CIME.case import Case
from CIME.utils import expect, run_cmd
from CIME.buildlib import parse_input
from CIME.build import get_standard_makefile_args

logger = logging.getLogger(__name__)

###############################################################################
def _build_rtm():
###############################################################################

    caseroot, libroot, bldroot = parse_input(sys.argv)

    with Case(caseroot) as case:
        casetools = case.get_value("CASETOOLS")
        gmake_j = case.get_value("GMAKE_J")
        gmake = case.get_value("GMAKE")

        # create Filepath file
        objroot = case.get_value("OBJROOT")
        filepath_file = os.path.join(objroot, "rof", "obj", "Filepath")
        driver = case.get_value("COMP_INTERFACE").lower()

        if not os.path.isfile(filepath_file):
            srcroot = case.get_value("SRCROOT")
            caseroot = case.get_value("CASEROOT")
            paths = [os.path.join(caseroot, "SourceMods", "src.rtm"),
                     os.path.join(srcroot, "components", "rtm", "src", "riverroute"),
                     os.path.join(srcroot, "components", "rtm", "src", "cpl", driver)]

            with open(filepath_file, "w") as filepath:
                filepath.write("\n".join(paths))
                filepath.write("\n")

        # build the library
        complib = os.path.join(libroot, "librof.a")
        makefile = os.path.join(casetools, "Makefile")

        cmd = "{} complib -j {} MODEL=rtm COMPLIB={} -f {} {}" \
            .format(gmake, gmake_j, complib, makefile, get_standard_makefile_args(case))

        rc, out, err = run_cmd(cmd, from_dir=bldroot)
        expect(rc == 0, "Command %s failed rc=%d\nout=%s\nerr=%s" % (cmd, rc, out, err))

        logger.info("Command %s completed with output %s\nerr %s", cmd, out, err)

###############################################################################

if __name__ == "__main__":
    _build_rtm()
